package com.songshuai.webapi.baseapi.utils;

import org.apache.commons.beanutils.BeanUtils;

import java.util.HashMap;
import java.util.Map;

public class BeanToMapUtil {
       
    public static Object mapToObject(Map<String, Object> map, Class<?> beanClass) throws Exception {
        if (map == null)  
            return null;  
   
        Object obj = beanClass.newInstance();  
   
        org.apache.commons.beanutils.BeanUtils.populate(obj, map);  
   
        return obj;  
    }    
       
    public static Map<String, Object> objectToMap(Object obj) {
        if(obj == null)  
            return null;

        Map map = new HashMap();
        map.putAll(new org.apache.commons.beanutils.BeanMap(obj));
        return map;
    }

    public static <T> T toBean(Map map, Class<T> clazz) {
        try {
            /*
             * 1. 通过参数clazz创建实例 2. 使用BeanUtils.populate把map的数据封闭到bean中
             */
            T bean = clazz.newInstance();
            // ConvertUtils.register(new DateConverter(), java.util.Date.class);
            BeanUtils.populate(bean, map);
            return bean;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
       
}  